import Vue from 'vue'
import Vuex from 'vuex'

import { login, getGroupInfo } from '@/api/user'

import { generatorDynamicRouter } from '@/router/generator-routers'
import storage from 'store'
import router from '@/router/index'
import actions from '@/micro/action'

Vue.use(Vuex)

export default new Vuex.Store({
  // modules: {
  //   app,
  //   user,
  //   permission
  // },
  state: {
    addRouters: [],
    flatRouters: [],
    compId: '',
    platId: ''
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
    },
    SET_COMP_ID: (state, compId) => {
      state.compId = compId
      actions.setGlobalState({ compId: state.compId, platId: state.platId })
    },
    SET_PLAT_ID: (state, platId) => {
      state.platId = platId
      actions.setGlobalState({ compId: state.compId, platId: state.platId })
    },
    SET_FLAT_ROUTERS: (state, flatRouters) => {
      state.flatRouters = flatRouters
    },
    CLEAR_STATE: (state) => {
      state.addRouters = []
      state.flatRouters = []
      state.compId = ''
    }
  },
  actions: {
// 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          if (res.retCode === 0) {
            const result = res.retObj
            storage.set('USERINFO', result, 24 * 60 * 60 * 1000)
            const params = {
              userId: result.userInfo.userId
            }
            resolve()
          } else {
            reject(res.retMsg)
          }
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    GetComp ({ commit }, params) {
      return new Promise((resolve, reject) => {
        getGroupInfo(params).then(res => {
          if (res.retCode === 0) {
            const list = res.retObj
            const compId = list[0].organCode
            const platId = list[0].seType
            commit('SET_PLAT_ID', platId)
            storage.set('PLAT_ID', platId)
            commit('SET_COMP_ID', compId)
            storage.set('COMP_ID', compId)
          }
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        storage.remove('USERINFO')
        storage.remove('COMP_ID')
        commit('CLEAR_STATE')
        router.push({ name: 'login' })
        resolve()
      })
    },

    // 生成
    GenerateRoutes ({ commit }, data) {
      commit('SET_FLAT_ROUTERS', data)
      return new Promise(resolve => {
        generatorDynamicRouter(data).then(routers => {
          commit('SET_ROUTERS', routers)
          resolve()
        })
      })
    }
  },
  plugins: []
})
